<?php
class RechargeAction extends CommonAction{

    public function _initialize() {
        header("Content-Type:text/html; charset=utf-8");
        $this->_inject_check(0);//调用过滤函数
        $this->_Config_name();//调用参数
        $this->_checkUser();
        //$this->checkSendType(13200223300);
    }

    public function cody(){
        //===================================二级验证
        $UrlID = (int) $_GET['c_id'];
        if (empty($UrlID)){
            $this->error('二级密码错误!');
            exit;
        }
        if(!empty($_SESSION['user_pwd2'])){
            $url = __URL__."/codys/Urlsz/$UrlID";
            $this->_boxx($url);
            exit;
        }
        $cody   =  M ('cody');
        $list	=  $cody->where("c_id=$UrlID")->field('c_id')->find();
        if ($list){
            $this->assign('vo',$list);
            $this->display('Public:cody');
            exit;
        }else{
            $this->error('二级密码错误!');
            exit;
        }
    }
    public function codys(){
        //=============================二级验证后调转页面
        $Urlsz = (int) $_POST['Urlsz'];
        if(empty($_SESSION['user_pwd2'])){
            $pass  = $_POST['oldpassword'];
            $fck   =  M ('fck');
            if (!$fck->autoCheckToken($_POST)){
                $this->error('页面过期请刷新页面!');
                exit();
            }
            if (empty($pass)){
                $this->error('二级密码错误!');
                exit();
            }

            $where = array();
            $where['id'] = $_SESSION[C('USER_AUTH_KEY')];
            $where['passopen'] = md5($pass);
            $list = $fck->where($where)->field('id,is_agent')->find();
            if($list == false){
                $this->error('二级密码错误!');
                exit();
            }
            $_SESSION['user_pwd2'] = 1;
        }else{
            $Urlsz = $_GET['Urlsz'];
        }
        switch ($Urlsz){
            case 1;
                $_SESSION['Urlszpass'] = 'MyssMangGuo';
                $bUrl = __URL__.'/currencyRecharge';//货币充值
                $this->_boxx($bUrl);
                break;
            case 2;
                $_SESSION['UrlPTPass'] = 'MyssGuanMangGuo';
                $bUrl = __URL__.'/adminCurrencyRecharge';//后台充值管理
                $this->_boxx($bUrl);
                break;
            case 3;
                $_SESSION['Urlszpass'] = 'MyssonlineRecharge';
                $bUrl = __URL__.'/onlineRecharge';
                $this->_boxx($bUrl);
                break;
            case 4;
                $_SESSION['UrlPTPass'] = 'MyssadminonlineRecharge';
                $bUrl = __URL__.'/adminonlineRecharge';
                $this->_boxx($bUrl);
                break;
            case 5;
                $_SESSION['UrlPTPass'] = 'MyssGuanMangGuo';
                $bUrl = __URL__.'/currencyPresent';//后台每日配币
                $this->_boxx($bUrl);
                break;

            default;
                $bUrl = __APP__;
                $this->_box(1,'二级密码已验证，无需重复操作！',$bUrl,1);
                exit;
        }
    }

    //==========================货币充值
    public function currencyRecharge(){
        if ($_SESSION['Urlszpass'] == 'MyssMangGuo'){
            $chongzhi = M('chongzhi');
            $fck = M('fck');
            $map['uid'] = $_SESSION[C('USER_AUTH_KEY')];

            $field  = '*';
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $chongzhi->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $Page = new ZQPage($count,$listrows,1);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $chongzhi->where($map)->field($field)->order('id desc')->page($Page->getPage().','.$listrows)->select();
            $this->assign('list',$list);//数据输出到模板
            //=================================================

            $where = array();
            $fwhere = array();
            $where['id'] = 1;
            $fwhere['id'] = $_SESSION[C('USER_AUTH_KEY')];
            $field = '*';
            $rs = $fck ->where($where)->field($field)->find();
            $frs = $fck ->where($fwhere)->field($field)->find();
            $this->assign('rs',$rs);
            $this->assign('frs',$frs);

            $nowdate[] =array();
            $nowdate[0] = date('Y');
            $nowdate[1] =date('m');
            $nowdate[2] =date('d');

            $this->assign('nowdate',$nowdate);

            $fee_rs = M ('fee') -> find();
            $this -> assign('s8',$fee_rs['s8']);
            $this -> assign('s9',$fee_rs['s9']);
            $this -> assign('s17',$fee_rs['s17']);
            $this -> assign('str6',$fee_rs['str6']);

            //88********************************************************************************************************
            $see = $_SERVER['HTTP_HOST'].__APP__;
            $see = str_replace("//","/",$see);

            $fee=M('fee');
            $fee_rs=$fee->find();
            $s13=$fee_rs['s13'];
            $s15=$fee_rs['s15'];


            $MD5key = $s15;		//MD5私钥
            $MerNo =$s13;					//商户号
            $BillNo =date('Ymd').rand(10000,99999);		//[必填]订单号(商户自己产生：要求不重复)
            $Amount = "0.01";				//[必填]订单金额

            $ReturnURL = "http://".$see."/Public/PayResult"; 			//[必填]返回数据给商户的地址(商户自己填写):::注意请在测试前将该地址告诉我方人员;否则测试通不过
            $Remark = "";  //[选填]升级。


            $md5src = $MerNo."&".$BillNo."&".$Amount."&".$ReturnURL."&".$MD5key;		//校验源字符串
            $SignInfo = strtoupper(md5($md5src));		//MD5检验结果


            $AdviceURL ="";   //[必填]支付完成后，后台接收支付结果，可用来更新数据库值
            $orderTime ="";   //[必填]交易时间YYYYMMDDHHMMSS
//			$defaultBankNumber ="BOCSH";   //[选填]银行代码s
            $defaultBankNumber ="";   //[选填]银行代码s

            //送货信息(方便维护，请尽量收集！如果没有以下信息提供，请传空值:'')
            //因为关系到风险问题和以后商户升级的需要，如果有相应或相似的内容的一定要收集，实在没有的才赋空值,谢谢。

            $products="products info";// '------------------物品信息


            $this -> assign('s13',$s13);
            $this -> assign('s15',$s15);
            $this -> assign('MerNo',$MerNo);
            $this -> assign('BillNo',$BillNo);
            $this -> assign('Amount',$Amount);
            $this -> assign('ReturnURL',$ReturnURL);
            $this -> assign('AdviceURL',$AdviceURL);
            $this -> assign('orderTime',$orderTime);
            $this -> assign('defaultBankNumber',$defaultBankNumber);
            $this -> assign('SignInfo',$SignInfo);
            $this -> assign('Remark',$Remark);
            $this -> assign('products',$products);
            //88********************************************************************************************************

            $this->display ('currencyRecharge');
            return;
        }else{
            $this->error ('错误!');
            exit;
        }
    }
    //动态生成md5的值
    public function make_md5(){
        $BillNo=$_POST['BillNo'];
        $Amount=$_POST['Amount'];

        $fee=M('fee');
        $fee_rs=$fee->find();
        $s13=$fee_rs['s13'];
        $s15=$fee_rs['s15'];


        $MD5key = $s15;		//MD5私钥
        $MerNo =$s13;					//商户号

        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $ReturnURL = "http://".$see."/Public/PayResult"; 			//[必填]返回数据给商户的地址(商户自己填写):::注意请在测试前将该地址告诉我方人员;否则测试通不过

        $md5src = $MerNo."&".$BillNo."&".$Amount."&".$ReturnURL."&".$MD5key;		//校验源字符串
        $SignInfo = strtoupper(md5($md5src));		//MD5检验结果
//        echo $md5src.'=='.md5($md5src).'====='.$SignInfo;
        echo $SignInfo;
    }
    public function user_money(){
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $fck=M('fck');
        $rs = $fck -> where('id='.$id)->field('is_pay,agent_use') -> find();
        $this -> assign('rs',$rs);
        $this->display ();
    }
    public function recharge_add(){
        //收到 的数据
        $BillNo=$_POST['BillNo'];
        $Amount=$_POST['Amount'];

        //用户信息
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $fck=M('fck');
        $rs = $fck -> where('id='.$id)->field('is_pay,user_id') -> find();
        $inUserID=$rs['user_id'];

        $chongzhi=M('chongzhi');
        $data = array();
        $data['uid']     = $id;
        $data['user_id'] = $inUserID;
        $data['huikuan'] = $Amount;
        $data['zhuanghao'] = $BillNo;
        $data['rdt']     = time();
        $data['epoint']  = $Amount;
        $data['is_pay']  = 0;
        $data['stype']  = 1;

        $chongzhi->add($data);
        echo 1;
    }
    public function czAC(){
        $fck = M('fck');

        $gouwu=A('Gouwu');
        $ePoints = (int) trim($_POST['amount']);

        if (empty($ePoints) || !is_numeric($ePoints)){
            $this->error('数量不能为空!');
            exit;
        }
        if ($ePoints <= 0){
            $this->error ('数量输入不正确!');
            exit;
        }

        $gouwu->ShoppingListAddAC(3,$ePoints,1,0);

    }

    public function rechargeAC(){
        $gouwu=D('Gouwu');
        $ePoints=$_POST['amount'];
        $fck = M ('fck');
        $ID = $_SESSION[C('USER_AUTH_KEY')];
        $rs = $fck -> field('is_pay,user_id') -> find($ID);
        // if($rs['is_pay'] == 0){
        //     $this->error('临时会员不能充值！');
        //     exit;
        // }
        if (empty($ePoints) || !is_numeric($ePoints)){
            $this->error('金额不能为空!');
            exit;
        }
        if (strlen($ePoints)>9){
            $this->error ('金额太大!');
            exit;
        }
        if ($ePoints<=0){
            $this->error ('金额格式不对!');
            exit;
        }
        $gouwu->ShoppingListAddAC(3,$ePoints,2);


    }




    public function currencyRechargeAC(){
        if ($_SESSION['Urlszpass'] == 'MyssMangGuo'){
            $fck = M ('fck');
            $ID = $_SESSION[C('USER_AUTH_KEY')];
            $rs = $fck -> field('is_pay,user_id,user_name,bank_name,bank_card,weixin,weixinCode') -> find($ID);
            if($rs['is_pay'] == 0){
                $this->error('临时会员不能充值！');
                exit;
            }

            // if (empty($rs['weixin']) or empty($rs['weixinCode'])){
            //     $this->error('充值前请先完善个人资料！');
            // }

            $inUserID=$rs['user_id'];
            $ePoints = trim($_POST['ePoints']);
            $stype = (int) trim($_POST['stype']);
            $stype = $stype == 1 ? 1 : ($stype == 2 ? 2 : 1);

            $chongzhi = M('chongzhi');
            if (!$chongzhi->autoCheckToken($_POST)){
                $this->error('页面过期，请刷新页面！');
                exit;
            }
            if (empty($ePoints) || !is_numeric($ePoints)){
                $this->error('金额不能为空!');
                exit;
            }
            if (strlen($ePoints)>9){
                $this->error ('金额太大!');
                exit;
            }
            if ($ePoints<=0){
                $this->error ('金额格式不对!');
                exit;
            }

            $id =  $_SESSION[C('USER_AUTH_KEY')];
            $where = array();
            $where['uid'] = $id;
            $where['is_pay'] = 0;
            $field1 = 'id';
            $vo3 = $chongzhi ->where($where)->field($field1)->find();
            if ($vo3){
                $this->error('上次充值还没通过审核!');
                exit;
            }

            //开始事务处理
            $chongzhi->startTrans();

            //充值表
//			$_money = trim($_POST['_money']);  //已汇款数额
//			$_money = $ePoints;  //已汇款数额
//			$_num = trim($_POST['_num']);  // 汇款到账号
//			$_year = trim($_POST['_year']); // 年
//			$_month = trim($_POST['_month']);  //月
//			$_date = trim($_POST['_date']);  //日
//			$_hour = trim($_POST['_hour']);  //小时
//			$_minute = trim($_POST['_minute']);  //小时


//			if (empty($_money) || !is_numeric($_money)){
//				$this->error('请输入数字或金额不能为空!');
//				exit;
//			}
//			if (empty($_num)){
//				$this->error('账号不能为空!');
//				exit;
//			}
//			if (empty($_year) || !is_numeric($_year)){
//				$this->error('请输入数字或年不能为空!');
//				exit;
//			}
//			if (empty($_month) || !is_numeric($_month)){
//				$this->error('请输入数字或月不能为空!');
//				exit;
//			}
//			if (empty($_date) || !is_numeric($_date)){
//				$this->error('请输入数字或日不能为空!');
//				exit;
//			}
//			if (empty($_hour) || !is_numeric($_hour)){
//				$this->error('请输入数字或小时不能为空!');
//				exit;
//			}
//			if (empty($_minute) || !is_numeric($_minute) || $_minute>60){
//				$this->error('请输入数字或分钟不能为空或者输入数字错误!');
//				exit;
//			}
//

            $nowdate = strtotime(date('c'));
//			$nowdate = strtotime(date($_year.'-'. $_month.'-'.$_date.' '. $_hour.':'.$_minute.':00'));

            $data = array();
            $data['uid']     = $id;
            $data['user_id'] = $inUserID;
//			$data['huikuan'] = $_money;
//			$data['zhuanghao'] = $_num;
            $data['rdt']     = $nowdate;
            $data['epoint']  = $ePoints;
            $data['is_pay']  = 0;
            $data['stype']  = $stype;
            $data['order_id']  = $this->_getOrderID();

            $rs2 = $chongzhi->add($data);

            unset($data,$id);
            if ($rs2){
                //提交事务
                $chongzhi->commit();
                $bUrl = __URL__.'/currencyRecharge';
                $this->_box(1,'充值申请成功，请等待后台审核！打款后请上传打款凭证，感谢您的支持和信任',$bUrl,1);
                exit;
            }else{
                //事务回滚：
                $chongzhi->rollback();
                $this->error('充值申请失败');
                exit;
            }
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    /*
     * 手动配送币
     * */
    public function currencyPresent(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $title = '配送币管理';
            $this->assign('title',$title);

            $UserID = $_REQUEST['UserID'];

            $ratio = $this->getFeeRule(['s27'])['s27'];  //配送币天数 ，比率
            $this->assign('ratio',$ratio);

            $time1=$this->_post('time1')? strtotime($this->_post('time1')) : 0;
            $time2=$this->_post('time2')? strtotime($this->_post('time2')) + 3600*24 -1 : "20000000000000";
            $map['create']=array(array('gt',$time1),array('lt',$time2));

            $xt_present_money = M('present_money');
            $map['id'] = ['gt', 0];
            $field  = '*';
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $xt_present_money->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $page_where = 'UserID=' . $UserID;//分页条件
            $Page = new ZQPage($count,$listrows,1, $page_where);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $xt_present_money->where($map)->field($field)->order('id desc')->page($Page->getPage().','.$listrows)->select();
            $this->assign('list',$list);//数据输出到模板
            //=================================================
            foreach ($list as $value){
                $findName[$value['id']] = M('fck')->where('id='.$value['uid'])->getField('user_name');
            }
            $this->assign('findName',$findName);//数据输出到模板
            $this->assign('list',$list);//数据输出到模板
            //=================================================


            if ($this->_post('time1')) {
                $this->assign('time1',$_POST['time1']);
            }
            if ($this->_post('time2')) {
                $this->assign('time2',$_POST['time2']);
            }


            $this->display();
            exit();
        }else{
            $this->error('错误!');
            exit;
        }
    }

    /**
     *手动配送币， 配送记录
     */
    public function currencyPresentAC(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $userID = trim($_POST['user_id']);
            $ePoints = trim($_POST['ePoints']);

            $present_days = (int) trim($_POST['present_days']);

            $fck = M ('fck');
            $rs = $fck ->where(['is_pay' => 1, 'user_id' => $userID]) -> find();
            if(!$rs || empty($rs)){
                $this->error('临时会员不能配送或 会员不正确！');
                exit;
            }
            $inUserID=$rs['user_id'];

            if (empty($ePoints) || !is_numeric($ePoints)){
                $this->error('金额不能为空!');
                exit;
            }
            if (strlen($ePoints)>9){
                $this->error ('金额太大!');
                exit;
            }
            if ($ePoints<=0){
                $this->error ('金额格式不对!');
                exit;
            }

            $rs2 = $this->createPresentMoney($rs, $ePoints);    //创建配币保存
            $this->checkSendType($rs, $ePoints);                //如果升级时， 配币发奖

            //配送记录
            unset($data,$id);
            if ($rs2){

                //提交事务
                $bUrl = __URL__.'/currencyPresent';
                $this->_box(1,'操作成功，请等待配送！',$bUrl,1);
                exit;
            }else{
                //事务回滚：
                $this->error('充值申请失败');
                exit;
            }
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    private function checkSendType($rs, $ePoints) {
        $num_record = M('present_money')->where(['uid' => $rs['id'], 'all_money_day' => ['gt', 0]])->count();

        if($num_record == 1) {
            return true;    //第一次发奖
        } else {
            $M_ulevel_up = M('ulevel_up');
            $ulevel_up = $M_ulevel_up->where(['is_pay' => 0, 'price' => 0])->order('create_time asc')->find();
            if(!$ulevel_up) return false;

            //更新 表 ulevel_up
            $data = [];
            $data['pdt']            = time();
            $data['is_pay']         = 1;
            $data['price']          = 1;
            $M_ulevel_up->where(['id' =>$ulevel_up])->add($data);
        }

    }

    //创建配币天数，保存
    public function createPresentMoney($rs, $ePoints) {
        $ratio_a = $this->getFeeRule(['s27'])['s27'];
        $present_days = $ratio_a[0];
        $ratio = $ratio_a[1];

        if ($present_days<=0){
            $this->error ('配送天数不对!');
            exit;
        }

        $data = [];
        $data['uid'] = $rs['id'];
        $data['user_id'] = $rs['user_id'];
        $data['all_money'] = $ePoints;
        $data['live_money'] = $ePoints;
        $data['all_day'] = $present_days;
        $data['live_day'] = $present_days;
        $data['ratio'] = $ratio;
        $data['create'] = time();
        $data['update'] = time();

        $e_day_money = bcmul($ePoints , $ratio/100, 2);
        //$e_day_money = bcdiv($e_day_money , $present_days, 2);
        $data['e_day_money'] = $e_day_money;    //每日发放金额

        $rs2 = M('present_money')->add($data);

        $u_sql = "update xt_fck SET 
                    present_money = present_money + {$ePoints}, 
                    present_day = present_day + {$present_days}
                    where id = {$rs['id']}";
       M('fck')->execute($u_sql);
        return $rs2;
    }


    /*
     * 减去手动配送的币
     * */
    public function currencyPresentSub(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $present_id = I('get.id');
            $present_rs = M('present_money')->where(['id' => $present_id])->find();
            if(!$present_rs) $this->error('配送单错误');
            $this->assign('present_rs', $present_rs);

            $this->display();
            exit();
        }else{
            $this->error('错误!');
            exit;
        }
    }

    /**
     *手动配送币， 配送记录
     */
    public function currencyPresentSubAC(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $present_id = I('post.presentid');
            $present_rs = M('present_money')->where(['id' => $present_id])->find();
            if(!$present_rs) $this->error('配送单错误');
            if($present_rs['live_money'] <= 0) $this->error('配送的剩余金额为零, 如需修改，请去修改已配的币');
            if($present_rs['live_day'] <= 0) $this->error('配送天数为0, 如需修改，请去修改已配的币');

            $fck = M ('fck');
            $rs = $fck ->where(['is_pay' => 1, 'user_id' => $present_rs['user_id']]) -> find();
            if(!$rs || empty($rs)){
                $this->error('临时会员不能配送或 会员不正确！');
                exit;
            }

            $ePoints    = I('post.ePoints');
            if (empty($ePoints) || !is_numeric($ePoints)){
                $this->error('金额不能为空!');
                exit;
            }
            if (strlen($ePoints)>9){
                $this->error ('金额太大!');
                exit;
            }
            if ($ePoints <= 0){
                $this->error ('金额格式不对! 减去的数请填写正数');
                exit;
            }
            if ($ePoints > $present_rs['live_money']){
                $this->error ('减去的金额不能超过剩余的金额');
                exit;
            }

            $rs2 = $this->subPresentMoney($rs, $present_rs, $ePoints);

            //配送记录
            unset($data,$id);
            if ($rs2){

                //提交事务
                $bUrl = __URL__.'/currencyPresent';
                $this->_box(1,'操作成功，请查看是否正确！',$bUrl,1);
                exit;
            }else{
                //事务回滚：
                $this->error('申请失败');
                exit;
            }
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    //减去 配送币
    private function subPresentMoney($rs, $present_rs, $ePoints=0) {
        $data = [];
        $data['live_money']     = $present_rs['live_money'] - $ePoints;
        $e_day_money            = bcdiv($data['live_money'], $present_rs['live_day'], 2);
        $data['e_day_money']    = $e_day_money;    //改变的每日发放金额
        $data['sub_money']      = $present_rs['sub_money'] + $ePoints;     //减少的金额
        $rs2 = M('present_money')->where(['id' => $present_rs['id']])->save($data);

        $u_sql = "update xt_fck SET 
                    present_money = present_money - {$ePoints}
                    where id = {$rs['id']}";
        M('fck')->execute($u_sql);
        return $rs2;
    }


    /*
     * 前台配送币，显示
     * */
    public function fontPresent(){
            $title = '配送币管理';
            $this->assign('title',$title);

            //$UserID = $_REQUEST['UserID'];
            $id = $_SESSION[C('USER_AUTH_KEY')];
            $fck_cu_rs = M('fck')->where(['id' => $id])->find();
            $UserID = $fck_cu_rs['user_id'];

            $ratio = $this->getFeeRule(['s27'])['s27'];  //配送币天数 ，比率
            $this->assign('ratio',$ratio);

            $time1=$this->_post('time1')? strtotime($this->_post('time1')) : 0;
            $time2=$this->_post('time2')? strtotime($this->_post('time2')) + 3600*24 -1 : "20000000000000";
            $map['create']=array(array('gt',$time1),array('lt',$time2));

            $xt_present_money = M('present_money');
            /*测试用，所有的用户
            $map['id'] = ['gt', 0];*/
            $map['uid'] = $id;
            $field  = '*';
            
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $xt_present_money->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $page_where = 'UserID=' . $UserID;//分页条件
            $Page = new ZQPage($count,$listrows,1, $page_where);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $xt_present_money->where($map)->field($field)->order('id desc')->page($Page->getPage().','.$listrows)->select();
            $this->assign('list',$list);//数据输出到模板
            //=================================================
            foreach ($list as $value){
                $findName[$value['id']] = M('fck')->where('id='.$value['uid'])->getField('user_name');
            }
            $this->assign('findName',$findName);//数据输出到模板
            $this->assign('list',$list);//数据输出到模板
            //=================================================


            if ($this->_post('time1')) {
                $this->assign('time1',$_POST['time1']);
            }
            if ($this->_post('time2')) {
                $this->assign('time2',$_POST['time2']);
            }

            $this->display();
    }





    //生成订单编号
    private function _getOrderID(){
        $cash = M('chongzhi');

        $firststr = $this->createRandomStr(1);
        $mynn = $firststr.rand(10000000,99999999);

        $fwhere['order_id'] = $mynn;
        $frss = $cash->where($fwhere)->field('id')->find();
        if ($frss){
            return $this->_getOrderID();
        }else{
            unset($cash);
            return $mynn;
        }
    }



    private function createRandomStr($length){
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
        $strlen = 26;
        while($length > $strlen){
            $str .= $str;
            $strlen += 26;
        }
        $str = str_shuffle($str);
        return substr($str,0,$length);
    }


    //==============================充值管理
    public function adminCurrencyRecharge(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $chongzhi = M ('chongzhi');
            $UserID = trim($_REQUEST['UserID']);
            if (!empty($UserID)){
//				$UserID = strtolower($UserID);
// 				$map['user_id'] = array('like',"%".$UserID."%");
                $map['user_id'] = array('eq',$UserID);
            }

            $order_id = trim($_REQUEST['order_id']);

            if (!empty($order_id)){

                $map['order_id'] = array('eq',$order_id);
            }

            $sdata = strtotime($_REQUEST['sNowDate']);
            $edata = strtotime($_REQUEST['endNowDate']);

            if(!empty($sdata) && empty($edata)){
                $map['pdt'] = array('gt',$sdata);
            }

            if(!empty($edata) && empty($sdata)){
                $enddata = $edata + 24*3600-1;
                $map['pdt'] = array('elt',$enddata);
            }



            if(!empty($sdata) &&  !empty($edata)){
                $enddatas = $edata + 24*3600-1;
                $map['_string'] = 'pdt >= '.$sdata.' and pdt <= '.$enddatas;
            }

            if ( $_POST['is_pay'] ==1){
                $map['is_pay'] = array('eq',1);
            }
            if ( $_POST['is_pay'] ==2){
                $map['is_pay'] = array('eq',0);
            }


            $field  = '*';
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $chongzhi->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $page_where = 'UserID=' . $UserID.'&sNowDate='.$_REQUEST['sNowDate'].'&endNowDate='.$_REQUEST['endNowDate'];//分页条件
            $Page = new ZQPage($count, $listrows, 1, 0, 3, $page_where);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $chongzhi->where($map)->field($field)->order('id desc')->page($Page->getPage().','.$listrows)->select();

            foreach ($list as $value){
                $findName[$value['id']] = M('fck')->where('id='.$value['uid'])->getField('user_name');
            }
            $this->assign('findName',$findName);//数据输出到模板
            $this->assign('list',$list);//数据输出到模板
            //=================================================


            $m_count = $chongzhi->where($map)->sum('epoint');

//            $map_su=$map;
//            $map_su['_string']="is_pay=1";
//            $su = $chongzhi->where($map_su)->sum('epoint');
//
//            $map_fa=$map;
//            $map_fa['_string']="is_pay=0";
//            $fa = $chongzhi->where($map_fa)->sum('epoint');

            $su=0;
            $fa=0;
            foreach ($list as $item){
                if($item['is_pay']){
                    $su+=$item['epoint'];
                }else{
                    $fa+=$item['epoint'];
                }
            }

            $this->assign('success_money',$su);
            $this->assign('false_money',$fa);
            $this->assign('m_count',$m_count);

            $title = '充值管理';
            $this->assign('title',$title);
            $this->display('adminCurrencyRecharge');
            exit();
        }else{
            $this->error('错误!');
            exit;
        }
    }
    public function adminCurrencyRechargeAC(){
        //处理提交按钮
        $action = $_POST['action'];
        //获取复选框的值
        $PTid = $_POST['tabledb'];
        $fck = M ('fck');
        if (!$fck->autoCheckToken($_POST)){
            $this->error('页面过期，请刷新页面！');
            exit;
        }
        if (!isset($PTid) || empty($PTid)){
            $bUrl = __URL__.'/adminCurrencyRecharge';
            $this->_box(1,'请选择！',$bUrl,1);
            exit;
        }
        switch ($action){
            case '确认';
                $this->_adminCurrencyRechargeOpen($PTid);
                break;
            case '删除';
                $this->_adminCurrencyRechargeDel($PTid);
                break;
            default;
                $bUrl = __URL__.'/adminCurrencyRecharge';
                $this->_box(0,'没有该记录！',$bUrl,1);
                break;
        }
    }

    public function adminCurrencyRechargeAdd(){
        //为会员充值
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $fck = M ('fck');
            if (!$fck->autoCheckToken($_POST)){
                $this->error('页面过期，请刷新页面！');
                exit;
            }
            $UserID = $_POST['UserID'];
            $UserID = strtolower($UserID);
            $ePoints = $_POST['ePoints'];
            $content = $_POST['content'];
            $stype = (int)$_POST['stype'];
            $stype = $stype == 1 ? 1 : ($stype == 2 ? 2 : 1);
            if (is_numeric($ePoints) == false){
                $this->error('金额错误，请重新输入！');
                exit;
            }
            if (!empty($UserID) && !empty($ePoints)){
                $where = array();
                $where['user_id'] = $UserID;
//				$where['is_pay'] = array('gt',0);
                $frs = $fck->where($where)->field('id,nickname,is_agent,user_id')->find();
                if ($frs){
                    $chongzhi = M ('chongzhi');
                    $data = array();
                    $data['uid']     = $frs['id'];
                    $data['user_id'] = $frs['user_id'];
                    $data['rdt']     = strtotime(date('c'));
                    $data['epoint']  = $ePoints;
                    $data['is_pay']  = 0;
                    $data['stype']  = $stype;
                    $data['get_fh'] = 1;
                    $result = $chongzhi->add($data);
                    $rearray[] = $result;
                    unset($data,$chongzhi);
                    $this->_adminCurrencyRechargeOpen($rearray);
                }else{
                    $this->error('没有该会员，请重新输入!');
                }
                unset($fck,$frs,$where,$UserID,$ePoints);
            }else{
                $this->error('错误!');
            }
        }else{
            $this->error('错误!');
        }
    }

    private function _adminCurrencyRechargeOpen($PTid){
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $chongzhi = M ('chongzhi');
            $fck = D('Fck');//
            $where = array();
            $where['is_pay'] = 0;
            $where['id'] = array ('in',$PTid);
            $rs = $chongzhi->where($where)->select();
            $fck_where = array();
            $nowdate = strtotime(date('c'));


            foreach($rs as $vo){
                $fck_where['id'] = $vo['uid'];
                $rsss = $fck->where($fck_where)->field('id,user_id,is_agent,p_path')->find();
                if ($rsss){
                    if ($vo['stype'] == 1){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值-九霄通宝",$vo['epoint'],"ztbl");
                    }
                    /*if ($vo['stype'] == 1){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值",$vo['epoint'],"agent_use");
                    }
                    if ($vo['stype'] == 2){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值TSP",$vo['epoint'],"tsp");
                    }*/

                    //$this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值",$vo['epoint'],"agent_use");
                    /*if ($vo['stype'] ==1){*/

                        /*if($vo['get_fh']!=1){
                        //计算业绩
                            $fck->where('id=1')->setInc('chuju',$vo['epoint']);//公司总业绩
                            $fck->where('id='.$vo['uid'])->setInc('cpzj',$vo['epoint']);//个人业绩
                            //团队业绩
                            $p_path = $fck->where('id in(0'.$rsss['p_path'].'0) and is_pay>0')->select();
                            foreach ($p_path as $key2 => $value2) {
                                $fck->where('id='.$value2['id'])->setInc('zjj',$vo['epoint']);//团队业绩
                            }
                                //计算奖金
                                //$fck->getusjj($vo['uid'],$vo['epoint']);
                        }*/
                            
                    /*}*/
                    /*if ($vo['stype'] ==0){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值奖金币",$vo['epoint'],"agent_use");
                    }
                    if ($vo['stype'] ==2){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值互助升级",$vo['epoint'],'');
                        $moe = $vo['epoint']*1.2;
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值互助升级赠送",$moe,'agent_cash');//1.2倍充值消费币
                        D('Fck')->jijin($vo['uid'],$vo['epoint']);//调用升级
                    }
                    if ($vo['stype'] ==3){
                        $this->zijin_log($vo['uid'],$vo['user_id'],"recharge","充值有效积分",$vo['epoint'],3);
                    }*/
                    $chongzhi->execute("UPDATE __TABLE__ set `is_pay`=1 ,`pdt`=$nowdate  where `id`=". $vo['id']);

                }
            }
            unset($chongzhi,$fck,$where,$rs,$fck_where);
            $bUrl = __URL__.'/adminCurrencyRecharge';
            $this->_box(1,'确认成功！',$bUrl,1);

        }else{
            $this->error('错误!');
            exit;
        }
    }
    private function _adminCurrencyRechargeDel($PTid){
        if ($_SESSION['UrlPTPass'] == 'MyssGuanMangGuo'){
            $User = M ('chongzhi');
            $where = array();
            //			$where['is_pay'] = 0;
            $where['id'] = array ('in',$PTid);
            $rs = $User->where($where)->delete();
            if ($rs){
                $bUrl = __URL__.'/adminCurrencyRecharge';
                $this->_box(1,'删除成功！',$bUrl,1);
                exit;
            }else{
                $bUrl = __URL__.'/adminCurrencyRecharge';
                $this->_box(0,'删除失败！',$bUrl,1);
                exit;
            }
        }else{
            $this->error('错误!');
            exit;
        }
    }

    //在线充值
    public function onlineRecharge(){
        if ($_SESSION['Urlszpass'] == 'MyssonlineRecharge'){
            $remit = M('remit');
            $fck = M('fck');
            $map['uid'] = $_SESSION[C('USER_AUTH_KEY')];
            $field  = '*';
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $remit->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $Page = new ZQPage($count,$listrows,1);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $remit->where($map)->field($field)->order('id desc')->page($Page->getPage().','.$listrows)->select();
            $this->assign('list',$list);//数据输出到模板
            //=================================================

            $fwhere = array();
            $fwhere['id'] = $_SESSION[C('USER_AUTH_KEY')];
            $field = '*';
            $frs = $fck ->where($fwhere)->field($field)->find();
            $this->assign('frs',$frs);
            $fee = M('fee');
            $fee_rs = $fee ->field('str10')-> find();
            $str4 = $fee_rs['str10'];//汇率
            //$str4 = 1;
            $this->assign('str4',$str4);

            $this->display ();
            return;
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    //在线充值订单确认
    public function onlineRechargeAC(){
        if ($_SESSION['Urlszpass'] == 'MyssonlineRecharge'){
            $fck = M ('fck');
            $remit = M('remit');

            $fee = M('fee');
            $fee_rs = $fee ->field('str10')-> find();
            $str4 = $fee_rs['str10'];//汇率
            //$str4 = 1;

            $id =  $_SESSION[C('USER_AUTH_KEY')];
            $rs = $fck -> field('is_pay,user_id') -> find($id);
            if($rs['is_pay']==0){
                $this->error('临时会员不能充值!');
                exit;
            }
            $inUserID=$rs['user_id'];

            $ePoints = trim($_POST['ePoints']);
            if (empty($ePoints) || !is_numeric($ePoints)){
                $this->error('金额不能为空!');
                exit;
            }
            if (strlen($ePoints)>9){
                $this->error ('金额太大!');
                exit;
            }
            if ($ePoints<=0){
                $this->error ('金额格式不对!');
                exit;
            }
            $ePoints = ((int)($ePoints*100))/100;
            $inmoney = $ePoints*$str4;
            $inmoney = ((int)($inmoney*100))/100;



            $orok = 0;
            while($orok==0){
                $orderid = $this->makeOrder();

                $where = array();
                $where['orderid'] = array('eq',$orderid);
                $nn = $remit->where($where)->count();
                if($nn==0){
                    $orok = 1;
                }
            }
            $bank_code = trim($_POST['bank_code']);
            $this->assign('orderid',$orderid);
            $this->assign('ePoints',$ePoints);
            $this->assign('inmoney',$inmoney);
            $this->assign('bank_code',$bank_code);
            $this->assign('inUserID',$inUserID);
            $this->display();
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    //提交在线充值
    public function onlineRechargeOK(){
        if ($_SESSION['Urlszpass'] == 'MyssonlineRecharge'){
            $fck = M ('fck');
            $remit = M('remit');
            $fee = M('fee');
            $fee_rs = $fee ->field('str10')-> find();
            $str4 = $fee_rs['str10'];//汇率
            //$str4 = 1;

            $id =  $_SESSION[C('USER_AUTH_KEY')];
            $rs = $fck -> field('is_pay,user_id') -> find($id);
            if(!$rs){
                $this->error('会员数据错误，请重新登录！');
                exit;
            }
            $inUserID = $rs['user_id'];

            $ePoints = trim($_POST['ePoints']);
            if (empty($ePoints) || !is_numeric($ePoints)){
                $this->error('金额不能为空!');
                exit;
            }
            if (strlen($ePoints)>9){
                $this->error ('金额太大!');
                exit;
            }
            if ($ePoints<=0){
                $this->error ('金额格式不对!');
                exit;
            }
            $ePoints = ((int)($ePoints*100))/100;
            $inmoney = $ePoints*$str4;
            $amount = ((int)($inmoney*100))/100;



            $orderid = trim($_POST['orderid']);

            $orok = 0;
            while($orok==0){
                if(empty($orderid)){
                    $orderid = $this->makeOrder();
                }
                $where = array();
                $where['orderid'] = array('eq',$orderid);
                $nn = $remit->where($where)->count();
                if($nn==0){
                    $orok = 1;
                }else{
                    $orderid = $this->makeOrder();
                }
            }

            $data = array();
            $data['uid']     = $id;
            $data['user_id'] = $inUserID;
            $data['amount'] = $ePoints;
            $data['kh_money'] = $amount;
            $data['or_time'] = mktime();
            $data['orderid'] = $orderid;
            $result = $remit->add($data);
            unset($data);

            if ($result){

                $hxb = A('Hxpay');

                $hxb->Hx_pay($orderid,$amount);


                $this->display("Hxpay_onlineRechargeOK");//环讯

            }else{
                $this->error('生成支付订单失败！');
                exit;
            }
        }else{
            $this->error ('错误!');
            exit;
        }
    }

    //后台管理在线充值
    public function adminonlineRecharge(){
        $this->_Admin_checkUser();
        if ($_SESSION['UrlPTPass'] == 'MyssadminonlineRecharge'){
            $remit = M('remit');
            $UserID = $_REQUEST['UserID'];
            $ss_type = (int) $_REQUEST['type'];
            if (!empty($UserID)){
                import ( "@.ORG.KuoZhan" );  //导入扩展类
                $KuoZhan = new KuoZhan();
                if ($KuoZhan->is_utf8($UserID) == false){
                    $UserID = iconv('GB2312','UTF-8',$UserID);
                }
                unset($KuoZhan);
                $map['user_id'] = array('like',"%".$UserID."%");
                $UserID = urlencode($UserID);
            }
            if($ss_type==1){
                $map['is_pay'] = array('egt',0);
            }elseif($ss_type==2){
                $map['is_pay'] = array('egt',1);
            }
            //查询字段
            $field  = '*';
            //=====================分页开始==============================================
            import ( "@.ORG.ZQPage" );  //导入分页类
            $count = $remit->where($map)->count();//总页数
            $listrows = C('ONE_PAGE_RE');//每页显示的记录数
            $page_where = 'UserID=' . $UserID . '&type=' . $ss_type;//分页条件
            $Page = new ZQPage($count, $listrows, 1, 0, 3, $page_where);
            //===============(总页数,每页显示记录数,css样式 0-9)
            $show = $Page->show();//分页变量
            $this->assign('page',$show);//分页变量输出到模板
            $list = $remit->where($map)->field($field)->order('or_time desc,id desc')->page($Page->getPage().','.$listrows)->select();
            $this->assign('list',$list);//数据输出到模板
            //=================================================


            $this->display ();
            return;
        }else{
            $this->error('数据错误!');
            exit;
        }
    }

    //后台处理在线充值
    public function adminonlineRechargeAC(){
        //处理提交按钮
        $action = $_POST['action'];
        //获取复选框的值
        $PTid = $_POST['tabledb'];
        if (!isset($PTid) || empty($PTid)){
            $bUrl = __URL__.'/adminonlineRecharge';
            $this->_box(0,'请选择内容！',$bUrl,1);
            exit;
        }
        switch ($action){
            case '删除';
                $this->adminonlineRechargeDel($PTid);
                break;
            default;
                $bUrl = __URL__.'/adminonlineRecharge';
                $this->_box(0,'没有该内容！',$bUrl,1);
                break;
        }
    }

    //后台处理在线充值-删除
    private function adminonlineRechargeDel($PTid=0){
        $this->_Admin_checkUser();
        if($_SESSION['UrlPTPass'] == 'MyssadminonlineRecharge'){
            $remit = M ('remit');
            $where['id'] = array ('in',$PTid);
            $where['is_pay'] = array ('eq',0);
            $trs = $remit->where($where)->delete();
            if ($trs){
                $bUrl = __URL__.'/adminonlineRecharge';
                $this->_box(1,'删除成功！',$bUrl,1);
                exit;
            }else{
                $this->error('删除失败！');
            }
        }else{
            $this->error('错误!');
        }
    }

    //生成订单号
    private function makeOrder(){
//     	$Order_pre='100';

        $Order = date("Y").date("m").date("d").date("H").date("i").date("s"). mt_rand(100000,999999);
        return  $Order;
    }



    //上传打款凭证
    public function upload_voucher(){
        $oid = trim($_GET['oid']);
        if (empty($oid)){
            $this->error('订单信息有误！');
        }
        $this->assign('oid',$oid);
        $this->display();
    }




    /**
     * 上传图片
     * **/
    public function upload_fengcai_pp() {
        if(!empty($_FILES)) {
            //如果有文件上传 上传附件
            $this->_upload_fengcai_pp();
        }
    }

    protected function _upload_fengcai_pp()
    {
        header("content-type:text/html;charset=utf-8");
        // 文件上传处理函数

        //载入文件上传类
        import("@.ORG.UploadFile");
        $upload = new UploadFile();

        //设置上传文件大小
        $upload->maxSize  = 1048576 * 2 ;// TODO 50M   3M 3292200 1M 1048576

        //设置上传文件类型
        $upload->allowExts  = explode(',','jpg,gif,png,jpeg');

        //设置附件上传目录
        $upload->savePath =  './Public/Uploads/image/voucher/';

        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb =  false;

        //设置需要生成缩略图的文件前缀
        $upload->thumbPrefix   =  'm_';  //生产2张缩略图

        //设置缩略图最大宽度
        $upload->thumbMaxWidth =  '800';

        //设置缩略图最大高度
        $upload->thumbMaxHeight = '600';

        //设置上传文件规则
//		$upload->saveRule = uniqid;
        $upload->saveRule = date("Y").date("m").date("d").date("H").date("i").date("s").rand(1,100);

        //删除原图
        $upload->thumbRemoveOrigin = true;

        if(!$upload->upload()) {
            //捕获上传异常
            $error_p=$upload->getErrorMsg();
            echo "<script>alert('".$error_p."');history.back();</script>";
        }else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            $U_path=$uploadList[0]['savepath'];
            $U_nname=$uploadList[0]['savename'];
            $U_inpath=(str_replace('./Public/','__PUBLIC__/',$U_path)).$U_nname;

            echo "<script>window.parent.form1.image1.value='".$U_inpath."';</script>";
            echo "<span style='font-size:12px;'>上传完成！</span>";
            exit;

        }
    }

    public function look_big(){
        $oid = (int)$_GET['oid'];
        $rs = M('chongzhi')->where('id='.$oid)->find();
        $this->assign('img',$rs['img']);
        $this->display();
    }

    public function zhifudingdan(){
        $oid = $_POST['oid'];
        $image = $_POST['image'];
        if (empty($image)){
            $this->error('请选择凭证！');
        }
        $chongzhi = M('chongzhi');
        $rs = $chongzhi->where('id='.$oid)->find();
        if ($rs){
            $data = array('img'=>$image);
            $set = $chongzhi->where('id='.$oid)->setField($data);
            if ($set){
                $bUrl = __URL__.'/currencyRecharge';
                $this->_box(1,'已上传，请耐心等待系统确认！',$bUrl,1);
            }else{
                $this->error('数据错误！');
            }
        }else{
            $this->error('订单信息有误！');
        }
    }

}
?>